package com.yehangtech.designpattern.行为型_迭代器模式.util;

import java.util.Objects;

public class MyArrayList<E> implements MyList<E>{
    transient Object[] elementData; // non-private to simplify nested class access

    private int size;
    private int offset;

    public MyArrayList() {
        this.elementData=new Object[20];
        this.size=20;
        this.offset=0;
    }



    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return this.size==0;
    }

    @Override
    public boolean contains(Object o) {
        for (Object elementDatum : elementData) {
            if (Objects.equals(elementDatum,o)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            private int t=0;
            @Override
            public boolean hasNext() {
                return t+1<elementData.length && elementData[t+1]!=null;
            }

            @Override
            public E next() {
                return (E) elementData[t++];
            }
        };
    }

    @Override
    public boolean add(E e) {
        elementData[offset++]=e;
        if (offset>=size){
            size*=2;
            Object[] temp=new Object[size];
            for (int i = 0; i < elementData.length; i++) {
                temp[i]=elementData[i];
            }
            this.elementData=temp;
            System.gc();
        }
        return true;
    }

    @Override
    public boolean remove(Object o) {
        for (Object elementDatum : elementData) {
            if (Objects.equals(elementDatum,o)){
                elementDatum=null;
            }
        }
        Object[] temp=new Object[size];
        int t=0;
        for (int i = 0; i < elementData.length; i++) {
            if (null!=elementData[i]){
                temp[t++]=elementData[i];
            }
        }
        this.elementData=temp;
        System.gc();
        return true;
    }

    @Override
    public void clear() {
        this.elementData=new Object[0];
        this.size=0;
        System.gc();
    }
}
